#version 330 core

layout (location = 0) in vec4 aPos;
layout (location = 1) in vec2 aUV;
layout (location = 2) in vec4 aBoneID1;
layout (location = 3) in vec4 aBoneID2;
layout (location = 4) in vec4 aBoneID3;
layout (location = 5) in vec4 aBoneID4;
layout (location = 6) in vec4 aBoneWeight1;
layout (location = 7) in vec4 aBoneWeight2;
layout (location = 8) in vec4 aBoneWeight3;
layout (location = 9) in vec4 aBoneWeight4;


const int MAX_BONES = 20;
uniform mat4 gBones[MAX_BONES];

out vec2 TexCoord;

uniform mat4 mvp;

vec4 calculate_bone_transform(vec4 modelPos) {
    mat4 bone_transform = mat4(0.0);


    for(int i = 0; i < 4; i++) {
        int boneId = int(aBoneID1[i]);
        bone_transform += gBones[boneId] * aBoneWeight1[i];
    }

    for(int i = 0; i < 4; i++) {
        int boneId = int(aBoneID2[i]);
        bone_transform += gBones[boneId] * aBoneWeight2[i];
    }

    for(int i = 0; i < 4; i++) {
        if (aBoneWeight3[i] > 0.0) {
            int boneId = int(aBoneID3[i]);
            bone_transform += gBones[boneId] * aBoneWeight3[i];
        }
    }

    for(int i = 0; i < 4; i++) {
        if (aBoneWeight4[i] > 0.0) {
            int boneId = int(aBoneID4[i]);
            bone_transform += gBones[boneId] * aBoneWeight4[i];
        }
    }



    return bone_transform * modelPos;
}

void main() {
    TexCoord = aUV;
    gl_Position = mvp * calculate_bone_transform(aPos);
}